﻿using Microsoft.IdentityModel.Tokens;
using SmartConference.Domain;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SmartConference.Api.Filter
{
    public class JWTHelper
    {
        private readonly IConfiguration _configuration;

        public JWTHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 创建包含用户信息的ClaimList
        /// </summary>
        /// <param name="authUser"></param>
        /// <returns></returns>
        private List<Claim> CreateClaimList(long id,string?  userName)
        {
            return new List<Claim>
            {
                new Claim(ClaimTypes.Name,userName),
                new Claim(ClaimTypes.NameIdentifier, id.ToString())
                // 其他Claims...
            };
            //var classType = typeof(T);
            ////Claim 载荷的类 List
            ////GetProperties 获取类型下所有的属性
            //return classType.GetProperties().Select(item => new Claim(item.Name, Convert.ToString(item.GetValue(authUser)) ?? string.Empty)).ToList();
        }

        /// <summary>
        /// 生成JWT Token
        /// </summary>
        /// <param name="UserInfo"></param>
        /// <returns></returns>
        public string CreateToken(long id, string? userName)
        {
            // 1. 定义需要使用到的Claims
            var claims = this.CreateClaimList(id,userName);

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],     //Issuer
                _configuration["Jwt:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddMinutes(30),    //expires
                signingCredentials               //Credentials
            );

            // 6. 将token变为string
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return token;
        }
    }
}
